<template>
    <div style="height:calc(100vh - 60px);">
        <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms " ref="preview_iframe" class="xx-iframe"></iframe>
    </div>
</template>

<script>
import API from '../api/index'
export default {
    name: 'CodeShow',
    components: {
    },
    data() {
        return {
            snippet: {}
        }
    },
    computed: {

    },
    mounted() {
        this.$store.commit('setCodeShow', true)
        this.getSnippetInfo()
        this.$root.$on('gotoVsCode', (e) => { // 监听事件，这里$root很重要，不懂去官网介绍
            this.gotoVsCode(e) // 调用父路由中的方法
        })
    },
    beforeDestroy() {

    },
    methods: {
        getSnippetInfo() {
            if (this.$route.query.snippet != null) {
                this.axios(API.snippet.getSnippet(this.$route.query.snippet)).then(res => {
                    this.snippet = res.data.data
                    if (res.data.data == null) {
                        this.$message.error('该代码片段已下架或者被删除！')
                        return
                    }
                    if (this.snippet.type == 1) {
                        const base = `<base href="${API.getServer()}common/getSnippetProjectFile/${this.snippet.id}/" />`
                        this.axios(API.snippetProject.getSnippetProjectFile(`${this.snippet.id}/index.html`)).then(res => {
                            this.$refs.preview_iframe.contentWindow.document.write(base + res.data) // 动态写入返回页面到iframe
                            this.$refs.preview_iframe.contentWindow.document.close()
                        }).catch((e) => {
                            console.log(e)
                        })
                    } else {
                        this.$refs.preview_iframe.contentWindow.document.write(this.snippet.content) // 动态写入返回页面到iframe
                        this.$refs.preview_iframe.contentWindow.document.close()
                    }
                }).catch((e) => {
                    console.log(e)
                })
            }
        },
        gotoVsCode() {
            this.$store.commit('setCodeShow', false)
            this.$router.push({ path: '/myvscode', query: { snippet: this.snippet.id } })
            // location.reload()
        }
    }
}
</script>

<style scoped>
    .xx-iframe{
        width:100%;
        height:100%;
        border: 0;
    }
</style>
